<!-- static/index.html -->
<!DOCTYPE html>
<html>

<head>
    <title>协作编辑器</title>
    <style>
        #editor {
            width: 800px;
            height: 400px;
            border: 1px solid #ccc;
            padding: 10px;
            margin: 20px auto;
            font-family: monospace;
            white-space: pre-wrap;
            /* 保留换行符 */
            overflow-y: auto;
        }

        .status {
            text-align: center;
            color: #666;
        }

        /* 添加新样式确保每行都能显示 */
        #editor div {
            min-height: 1em;
        }
    </style>
</head>

<body>
    <div id="editor" contenteditable="true"></div>
    <div class="status">状态: <span id="status">未连接</span></div>

    <script>
        const editor = document.getElementById('editor');
        const statusSpan = document.getElementById('status');
        let ws;
        let isLocalChange = false;
        let composing = false;

        function connect() {
            ws = new WebSocket('ws://localhost:8090/user/ws');

            ws.onopen = () => {
                statusSpan.textContent = '已连接';
                statusSpan.style.color = 'green';
                // 连接建立后立即发送当前内容
                sendContent();
            };

            ws.onmessage = (event) => {
                const data = JSON.parse(event.data);
                if (!isLocalChange) {
                    isLocalChange = true;
                    if (data.type === 'INIT' || data.type === 'UPDATE') {
                        // 处理接收到的内容
                        const lines = data.content.split('\n');
                        editor.innerHTML = lines.map(line =>
                            `<div>${line || '<br>'}</div>`
                        ).join('');
                    }
                    isLocalChange = false;
                }
            };

            ws.onclose = () => {
                statusSpan.textContent = '已断开';
                statusSpan.style.color = 'red';
                setTimeout(connect, 1000);
            };
        }

        // 处理输入法事件
        editor.addEventListener('compositionstart', () => {
            composing = true;
        });

        editor.addEventListener('compositionend', () => {
            composing = false;
            sendContent();
        });

        // 处理回车事件
        editor.addEventListener('keydown', (e) => {
            if (e.key === 'Enter') {
                e.preventDefault();
                // 获取当前选区
                const selection = window.getSelection();
                const range = selection.getRangeAt(0);

                // 创建新的 div 元素
                const newDiv = document.createElement('div');
                newDiv.innerHTML = '<br>';

                // 获取当前行的 div
                let currentDiv = range.startContainer;
                while (currentDiv && currentDiv.nodeName !== 'DIV') {
                    currentDiv = currentDiv.parentNode;
                }

                // 如果在行末，插入新行
                if (currentDiv) {
                    const textAfterCursor = currentDiv.textContent.substring(range.startOffset);
                    currentDiv.textContent = currentDiv.textContent.substring(0, range.startOffset);
                    if (textAfterCursor) {
                        newDiv.textContent = textAfterCursor;
                    }
                    currentDiv.parentNode.insertBefore(newDiv, currentDiv.nextSibling);
                } else {
                    editor.appendChild(newDiv);
                }

                // 移动光标到新行开始处
                range.selectNodeContents(newDiv);
                range.collapse(true);
                selection.removeAllRanges();
                selection.addRange(range);

                sendContent();
            }
        });

        // 处理内容变化
        editor.addEventListener('input', (e) => {
            if (!composing && !isLocalChange) {
                sendContent();
            }
        });

        // 处理删除操作
        editor.addEventListener('keyup', (e) => {
            if ((e.key === 'Delete' || e.key === 'Backspace') && !composing && !isLocalChange) {
                sendContent();
            }
        });

        function sendContent() {
            // 收集所有文本内容，保留换行
            let content = '';
            for (const div of editor.children) {
                if (content) content += '\n';
                content += div.textContent;
            }

            const message = {
                type: 'UPDATE',
                content: content
            };
            console.log('Sending:', message);
            ws.send(JSON.stringify(message));
        }

        connect();
    </script>
</body>

</html>